package com.novabluetooth.services.servicedevices;

import android.annotation.SuppressLint;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.novabluetooth.services.bean.CDKinfo;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * BLE服务
 * @author JiangYL
 */
@SuppressLint("NewApi")
public class CardioChekService extends Service {
	private final static String TAG = CardioChekService.class.getSimpleName();
	private BluetoothManager mBluetoothManager;
	private BluetoothAdapter mBluetoothAdapter;
	private String mBluetoothDeviceAddress;
	private BluetoothGatt mBluetoothGatt;

	private int mConnectionState = STATE_DISCONNECTED;

	public final static String ACTION_GATT_CONNECTED = "com.nova.bt_example.ACTION_GATT_CONNECTED";
	public final static String ACTION_GATT_DISCONNECTED = "com.nova.bt_example.ACTION_GATT_DISCONNECTED";
	public final static String ACTION_GATT_SERVICES_DISCOVERED = "com.nova.bt_example.ACTION_GATT_SERVICES_DISCOVERED";
	public final static String ACTION_DATA_AVAILABLE = "com.nova.bt_example.ACTION_DATA_AVAILABLE";
	public final static String EXTRA_DATA = "com.nova.bt_example.le.EXTRA_DATA";

	private String mDeviceAddress = "E0:E5:CF:74:31:39";//蓝牙设备地址00:15:83:30:80:CC

	public final static UUID UUID_SERVICE =
			UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");//蓝牙设备的Service的UUID --0000ffe0

	public final static UUID UUID_NOTIFY =
			UUID.fromString("0000fff4-0000-1000-8000-00805f9b34fb");//蓝牙设备的Characteristic的UUID --0000ffe1

	public static final int STATE_DISCONNECTED = 0;
	private static final int STATE_CONNECTING = 1;
	private static final int STATE_CONNECTED = 2;

	/**GATT回调*/
	private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
		@Override
		public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
			if (newState == BluetoothProfile.STATE_CONNECTED) {
				mConnectionState = STATE_CONNECTED;
				gatt.discoverServices();//必须有，可以让onServicesDiscovered显示所有Services
				/*连接成功*/
				broadcastUpdate(CardioChekService.ACTION_GATT_CONNECTED);
				/*发现服务*/
				mBluetoothGatt.discoverServices();
			} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
				mConnectionState = STATE_DISCONNECTED;
				/*断开连接*/
				broadcastUpdate(CardioChekService.ACTION_GATT_DISCONNECTED);
				close();
			}
		}

		@Override
		public void onServicesDiscovered(BluetoothGatt gatt, int status) {
			if (status == BluetoothGatt.GATT_SUCCESS) {
				BluetoothGattService service = gatt.getService(UUID_SERVICE);
				BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID_NOTIFY);
				//连接
				mBluetoothGatt.setCharacteristicNotification(characteristic, true);
				/*发现服务*/
				broadcastUpdate(CardioChekService.ACTION_GATT_SERVICES_DISCOVERED);
			}
		}

		@Override
		public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
			if (status == BluetoothGatt.GATT_SUCCESS) {
//				Toast.makeText(BluetoothLeService.this,"",Toast.LENGTH_SHORT).show();
				/*读到数据*/
				broadcastUpdate(CardioChekService.ACTION_DATA_AVAILABLE, characteristic);
				Log.e("read--ch-",characteristic.getValue().toString());
				/*释放连接*/
				disconnect();

			}
		}
		@Override
		public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {

			broadcastUpdate(CardioChekService.ACTION_DATA_AVAILABLE, characteristic);
		}
	};

	/**发送单纯广播*/
	private void broadcastUpdate(final String action) {
		final Intent intent = new Intent(action);
		sendBroadcast(intent);
	}

	/**发送数据广播*/
	private void broadcastUpdate(final String action, final BluetoothGattCharacteristic characteristic) {
		final Intent intent = new Intent(action);
		String dataStr = new String(characteristic.getValue());
		sbf.append(dataStr);
		Log.e("StringBuffer--",sbf.toString());
		result = getData(sbf.toString());
		Log.e("result.Stute=",Stute+",isredata="+isReData);
		if(Stute == 0 && isReData == 0){
			result.setgetIsReData(0);
			Log.e("result=--",result.toString());
			sbf.setLength(0);
			disconnect();
		}else{
			isReData = -1;
			Stute = -1;
			result.setgetIsReData(-1);
		}
		intent.putExtra(CardioChekService.EXTRA_DATA, result);
		sendBroadcast(intent);
	}

	public class LocalBinder extends Binder {
		public CardioChekService getService() {
			return CardioChekService.this;
		}
	}
	int isReData = 0;
	StringBuffer sbf = new StringBuffer("");
	CDKinfo result;
	/**
	 * 处理数据返回bean
	 * @param data
	 * @return
	 */
	List<String> arrList;
	int Stute = -1;
	public CDKinfo getData(String data){
		//匹配双引号的正则表达式
		String pattStr = "(?<=\").*?(?=\")";
		//创建Pattern并进行匹配
		Pattern pattern= Pattern.compile(pattStr);
		Matcher matcher=pattern.matcher(data);
		arrList = new ArrayList<String>();
		//将所有匹配的结果打印输出
		while(matcher.find()) {
			String subData = matcher.group().trim();
			if(!subData.isEmpty()) {
				arrList.add(subData);
			}
		}
		Log.e("arrList--",arrList.toString());
		CDKinfo cdkData;
		if(arrList.size()==6){
			Log.e("arrList-23423-","weee");
			cdkData = subString(arrList);
			Stute = 0 ;
			isReData = 0;
			cdkData.setStute(0);
		}else {
			Log.e("arrList-8899-","8899");
			cdkData = new CDKinfo();
//			cdkData.setStute(-1);
			Stute = -1;
		}
		return cdkData;
	}

	/**
	 * 拆分截串
	 * @param data
	 * @return
	 */
	public CDKinfo subString(List<String> data) {
		CDKinfo cdk = new CDKinfo();
		String spStr = "";
		List<String> reData = new ArrayList<String>();
		for(int i = 0;i<=data.size();i++) {
			//不拆分最后一个元素
			if(i<(data.size()-1)) {
				spStr = data.get(i);
				String newStr = spStr.substring(spStr.indexOf(":")+1);
				reData.add(newStr);
			}else if(i==(data.size()-1)){
				String[] st = data.get(i).split(":");
				String splitStr = st[0].trim()+" : "+st[1].trim();
				reData.add(splitStr);

				Log.e("ListData---",reData.toString());
				cdk.setNumber("Number :"+reData.get(0));
				cdk.setDate("Date :"+reData.get(1));
				cdk.setTime("Time :" +reData.get(2));
				cdk.setModle("Modle :"+reData.get(4));
				cdk.setType(reData.get(5));
			}
		}
		return cdk;
	}


	@Override
	public void onCreate() {
		super.onCreate();
		Log.d(TAG, "onCreate");
	}

	@Override
	public IBinder onBind(Intent intent) {
		Log.d(TAG, "onBind");
		return mBinder;
	}

	@Override
	public boolean onUnbind(Intent intent) {
		Log.d(TAG, "onUnbind");
		close();
		return super.onUnbind(intent);
	}

	private final IBinder mBinder = new LocalBinder();

	/**判断是否初始化*/
	public boolean initialize() {
		if (mBluetoothManager == null) {
			mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
			if (mBluetoothManager == null) {
				Log.e(TAG, "Unable to initialize BluetoothManager.");
				return false;
			}
		}

		mBluetoothAdapter = mBluetoothManager.getAdapter();
		if (mBluetoothAdapter == null) {
			Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
			return false;
		}

		return true;
	}

	/**连接*/
	public boolean connect(final String address) {
		if (mBluetoothAdapter == null || address == null) {
			return false;
		}

		if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) {
			if (mBluetoothGatt.connect()) {
				mConnectionState = STATE_CONNECTING;
				return true;
			} else {
				return false;
			}
		}

		final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
		if (device == null) {
			return false;
		}
		mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
		mBluetoothDeviceAddress = address;
		mConnectionState = STATE_CONNECTING;
		return true;
	}

	/**断开连接*/
	public void disconnect() {
		if (mBluetoothAdapter == null || mBluetoothGatt == null) {
			return;
		}
		mBluetoothGatt.disconnect();
	}

	/**关闭*/
	public void close() {
		if (mBluetoothGatt != null) {
			mBluetoothGatt.close();
			mBluetoothGatt = null;
		}
	}
}
